<?php

namespace App\Http\Controllers;

use App\Model\User;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;

class WxController extends Controller {

    // wx
    public function wechat(Request $request) {

        $options = [
            'debug'  => env('WX_DEBUG'),
            'app_id' => env('WX_APP_ID'),
            'secret' => env('WX_SECRET'),
            'token'  => env('WX_TOKEN'),
        ];

        $app         = new Application($options);
        $server      = $app->server;
        $userService = $app->user;
        $qrcode      = $app->qrcode;

        $server->setMessageHandler(function ($message) use ($userService,$qrcode) {
            if ($message->MsgType = 'event') {
                return $this->guanzi($message, $userService,$qrcode);
            }
        });


        $response = $server->serve();
        return $response;
    }

    // 关注操作
    protected function guanzi($message, $userService,$qrcode) {
        switch ($message->Event) {
            case 'subscribe':
                $openid           = $message->FromUserName;
                $user             = $userService->get($openid);
                $data['openid']   = $openid;
                $data['nickname'] = $user->nickname;
                $data['headimg']  = $user->headimgurl;
                $data['subtime']  = time();
                $ret              = User::create($data);
                $result = $qrcode->forever($ret->uid);
                $ticket = $result->ticket;
                $url = $qrcode->url($ticket);
                $user_model = User::find($ret->uid);
                $user_model->qrimg = $url;
                $user_model->save();
                return '欢迎你：' . $ret->uid . '---' . $data['nickname'];
                break;
            case 'unsubscribe':
                $openid = $message->FromUserName;
                $user   = User::where('openid', $openid)->first();
                if ($user) {
                    $user->status = 2;
                    $user->save();
                }
                break;
            default:
                break;
        }
    }

    public function aa() {
        /*$data['openid']   = '111'.time();
        $data['nickname'] = '小明';
        $data['headimg']  = 'afdsafsa';
        $data['subtime']  = time();
        $ret = User::create($data);
        echo $ret->uid;*/
    }
}
